from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
import time,os
from shop.settings import BASE_DIR
from django.core.paginator import Paginator
from django.db.models import Q
from . import cateviews,userviews
from django.contrib.auth.decorators import permission_required
# Create your views here.

#查询
@permission_required('myadmin.create_Goods',raise_exception=True)
def addgoods(request):
    # 查询所有的分类  进行返回
    types = cateviews.tab()
    return render(request,'myadmin/goods/addgoods.html',{'types':types})

#添加

@permission_required('myadmin.create_Goods',raise_exception=True)
def goodsinsert(request):
    #接收post请求传入的数据并转化为字典
    ginfo = request.POST.dict()
    #删除字典中的csrfmiddlewaretoken
    ginfo.pop('csrfmiddlewaretoken')
    #获取图片的路径
    file = request.FILES.get('g_url')
    #判断是否为假
    if not file:
        #如果为假 返回提示信息并回到上一级页面
        return HttpResponse('<script>alert("请选择图片");history.back(-1)</script>')

    # 调用重命名函数给上传的图片重命名
    g_url=userviews.upload(file)

    # 入库
    goods = models.Goods()
    goods.title=ginfo['title']
    goods.ordernum=ginfo['ordernum']
    goods.g_url=g_url
    goods.price=ginfo['price']
    goods.ginfo=ginfo['ginfo']
    goods.cateid=models.Cates.objects.get(id=ginfo['cateid'])
    goods.save()
    return HttpResponse('<script>alert("添加成功");location.href="/myadmin/goodslist"</script>')


#查询
@permission_required('myadmin.create_Goods',raise_exception=True)
def goodslist(request):
    # 查询数据库的所有数据
    goods = models.Goods.objects.all()

    #搜索功能
    #接受类型
    types = request.GET.get('type')
    #接受关键字
    search = request.GET.get('search')

    for i in goods:
    #判断是否搜索内容
        if types:
            if types=='all':
                goods = models.Goods.objects.filter(Q(title__contains=search)|Q(price__contains=search))
            #查询
            elif types=='titlegoods':
                goods = models.Goods.objects.filter(Q(title__contains=search))
            elif types=='pricegoods':
                goods = models.Goods.objects.filter(Q(price__contains=search))



#     # 实例化分页对象
    p = Paginator(goods, 5)

    #一共可以分多少页
    sumpage=p.num_pages
# num_pages

    # 取第几页的数据
     # 接受用户的页码
    page = int(request.GET.get('p',1))
    # 第几页的数据
    page1 = p.page(page)

    # 判断 如果用输入的页码<=3 显示前五个页码
    if page<=3:
        # 页码的迭代序列  [1,2,3,4,5,6,7]
        prange = p.page_range[:5]
    elif page+2>=sumpage:
        prange = p.page_range[-5:]
    else:
        prange = p.page_range[page-3:page+2]







    return render(request,'myadmin/goods/goodslist.html',{'goods':page1,'prange':prange,'page':page,'sumpage':sumpage})


#修改
@permission_required('myadmin.create_Goods',raise_exception=True)
def editgoods(request):
    #接收用户id
    uid = request.GET.get('uid')
    #判断传输类型，如果是get 直接跳转到修页面
    if request.method=="GET":
        goods = models.Goods.objects.get(id=uid)
        godid = goods.cateid_id
        types = cateviews.tab()
        return render(request,'myadmin/goods/ditgoods.html',{'goods':goods,'types':types,'godid':godid})

    elif request.method=='POST':
            #获取提交的数据并转化为字典
            goodst = request.POST.dict()
            print(goodst)
            #获取当前的数据
            uinfo = models.Goods.objects.get(id=uid)
            #更新数据

            #标题
            uinfo.title = goodst['title']
            #单价
            uinfo.price = goodst['price']
            #库存
            uinfo.ordernum = goodst['ordernum']
            #判断图片是否上传
            file = request.FILES.get('g_url')
            if file:
                #有新商品图上传，则删除旧图片
                #   注'.'为当前项目下（manage.py同级目录）
                os.remove('.'+uinfo.g_url)
                #将新的图片重命名后赋予headurl变量
                headurl = userviews.upload(file)
                #重新赋值
                uinfo.g_url=headurl
            #商品简介
            uinfo.ginfo = goodst['ginfo']
            uinfo.save()
            return HttpResponse("<script>alert('修改成功');location.href='/myadmin/goodslist/';</script>")
#删除
def delgoods(request):
    uid = request.GET.get('uid')
    user = models.Goods.objects.get(id=uid)
    user.delete()
    return redirect(reverse('myadmin_goodslist'))



